<template>
  <div :id="name" :style="echartStyle"></div>
</template>
<script setup>
import { onBeforeUnmount, onMounted, ref, toRef, watch } from 'vue'

import * as Echarts from 'echarts'
const prop = defineProps({
  name: String,
  echartStyle: Object,
  option: Object,
  onClick: Object
})
let echartsModel = ref(null)
watch(
  () => prop.option,
  () => {
    initEchart()
  }
)
watch(
  () => prop.echartStyle,
  () => {
    if (echartsModel) {
      this.echartsModel.resize()
    }
  }
)

const initEchart = () => {
  echartsModel = Echarts.init(document.getElementById(prop.name))
  echartsModel.clear()
  echartsModel.showLoading('default', {
    text: '加载中',
    color: '#409EFF',
    textColor: '#409EFF',
    maskColor: 'rgba(0, 0, 0, 0.5)',
    zlevel: 0
  })
  echartsModel.setOption(prop.option)
  echartsModel.off('click')
  if (prop.onClick) {
    echartsModel.on('click', (param) => {
      context.emit('chartClick', param)
    })
  }
  echartsModel.hideLoading()
}

const drawResize = () => {
  if (echartsModel) {
    echartsModel.resize()
  }
}
onMounted(() => {
  window.addEventListener('resize', drawResize, 20)
  initEchart()
})
onBeforeUnmount(() => {
  echartsModel.dispose()
  window.removeEventListener('resize', drawResize, 20)
})


</script>